/**
Copyright [2008] [Julian Gamble] 

Licensed under the Apache License, Version 2.0 (the "License"); 
you may not use this file except in compliance with the License. 
You may obtain a copy of the License at 

	http://www.apache.org/licenses/LICENSE-2.0 
	
Unless required by applicable law or agreed to in writing, software 
distributed under the License is distributed on an "AS IS" BASIS, 
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
See the License for the specific language governing permissions and 
limitations under the License. 
 **/
package aerith.components;

import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Composite;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Insets;
import java.awt.LayoutManager;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.swing.SwingUtilities;

import org.jdesktop.swingx.JXImagePanel;

public class AerithContentJXImagePanel extends JXImagePanel {
    ////////////////////////////////////////////////////////////////////////////
    // THEME SPECIFIC FIELDS
    ////////////////////////////////////////////////////////////////////////////
    
    /**
	 * 
	 */
	private static final long serialVersionUID = -1008821566884313314L;

	private GradientPaint backgroundGradient = new GradientPaint(
    		new Point(0,105), Color.decode("#202737"), 
    		new Point(0,432), Color.decode("#8590A5"));
    
    private BufferedImage light;
    
    private float lightOpacity = 0.5f;
    
    public AerithContentJXImagePanel() {
    	super();
    	loadImages();
    }
    
    public AerithContentJXImagePanel(Image img) {
    	super();
    	if (img.getWidth(null) == -1 || img.getHeight(null) == -1)
			System.out.println("Image not loaded");
    	
    	super.setImage(img);
    	loadImages();
    }
    
    /**
     * Create a new buffered JPanel with the specified layout manager
     *
     * @param layout  the LayoutManager to use
     */
    public AerithContentJXImagePanel(LayoutManager layout) {
    	setLayout(layout);
        setDoubleBuffered(true);
        //setUIProperty("opaque", Boolean.TRUE);
        updateUI();
        
        loadImages();
    }

    private void loadImages() {
    	light = loadImage("/swing/content-light.png");
		
	}
    
    private BufferedImage loadImage(String resourcePath) {
    	java.net.URL imageurl = this.getClass().getResource(resourcePath);
    	BufferedImage result = null;
    	try {
			result =  javax.imageio.ImageIO.read(imageurl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
    }

	@Override
    protected void paintComponent(Graphics g)  {
        if (!isVisible()) {	
            return;
        }
        
        //super.paintComponent(g);
        
        Graphics2D g2 = (Graphics2D) g;
        
        Composite composite = g2.getComposite();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        g2.setPaint(backgroundGradient);
        Rectangle bounds = g2.getClipBounds();
        g2.fillRect(bounds.x, bounds.y, bounds.width, bounds.height);
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,
                         lightOpacity));
        
        g2.drawImage(light, 0, 0, getWidth(), light.getHeight(), null);
        g2.setComposite(composite);
        
        //Hacked from parent method
        
        paintJXImagePanel(g2, super.getImage(), super.getStyle());
        
        //g2.drawImage(img, insets.left, insets.top, this);
 //       g2.drawImage(super.getImage(), getInsets().left, getInsets().top, this);
        //g2.drawImage(img, insets.left, insets.top, pw, ph, null);
 //       g2.drawImage(super.getImage(), getInsets().left, getInsets().top, 
 //       		(getWidth() - getInsets().left - getInsets().right), 
 //       		(getHeight() - getInsets().top - getInsets().bottom), this);
    }

	private void paintJXImagePanel(Graphics2D g2, Image img, Style style) {
		//Graphics2D g2 = (Graphics2D)g;
        if (img != null) {
            final int imgWidth = img.getWidth(null);
            final int imgHeight = img.getHeight(null);
            if (imgWidth == -1 || imgHeight == -1) {
                //image hasn't completed loading, return
                return;
            }
            
            Insets insets = getInsets();
            final int pw = getWidth() - insets.left - insets.right;
            final int ph = getHeight() - insets.top - insets.bottom;
            
            
            
            switch (style) {
                case CENTERED:
                	
                    Rectangle clipRect = g2.getClipBounds();
                    int imageX = (pw - imgWidth) / 2 + insets.left;
                    int imageY = (ph - imgHeight) / 2 + insets.top;
                    Rectangle r = SwingUtilities.computeIntersection(imageX, imageY, imgWidth, imgHeight, clipRect);
                    if (r.x == 0 && r.y == 0 && (r.width == 0 || r.height == 0)) {
                        return;
                    }
                    //I have my new clipping rectangle "r" in clipRect space.
                    //It is therefore the new clipRect.
                    clipRect = r;
                    //since I have the intersection, all I need to do is adjust the
                    //x & y values for the image
                    int txClipX = clipRect.x - imageX;
                    int txClipY = clipRect.y - imageY;
                    int txClipW = clipRect.width;
                    int txClipH = clipRect.height;

                    //g2.drawImage(img, clipRect.x, clipRect.y, clipRect.x + clipRect.width, clipRect.y + clipRect.height,
                    //        txClipX, txClipY, txClipX + txClipW, txClipY + txClipH, null);
                    g2.drawImage(img, clipRect.x, clipRect.y, clipRect.x + clipRect.width, clipRect.y + clipRect.height,
                            txClipX, txClipY, txClipX + txClipW, txClipY + txClipH, this);
                    break;
                case TILED:
                    g2.translate(insets.left, insets.top);
                    Rectangle clip = g2.getClipBounds();
                    g2.setClip(0, 0, pw, ph);
                    
                    int totalH = 0;
                    
                    while (totalH < ph) {
                        int totalW = 0;
                        
                        while (totalW < pw) {
                            g2.drawImage(img, totalW, totalH, null);
                            totalW += img.getWidth(null);
                        }
                        
                        totalH += img.getHeight(null);
                    }
                    
                    g2.setClip(clip);
                    g2.translate(-insets.left, -insets.top);
                    break;
                case SCALED:
                    g2.drawImage(img, insets.left, insets.top, pw, ph, null);
                    break;
                case SCALED_KEEP_ASPECT_RATIO:
                    int w = pw;
                    int h = ph;
                    final float ratioW = ((float) w) / ((float) imgWidth);
                    final float ratioH = ((float) h) / ((float) imgHeight);
                    
                    if (ratioW < ratioH) {
                        h = (int)(imgHeight * ratioW);
                    } else {
                        w = (int)(imgWidth * ratioH);
                    }
                    
                    final int x = (pw - w) / 2 + insets.left;
                    final int y = (ph - h) / 2 + insets.top;
                    g2.drawImage(img, x, y, w, h, null);
                    break;
                default:
                    //LOG.fine("unimplemented");
                    g2.drawImage(img, insets.left, insets.top, this);
                    break;
            }
        } else {
        	System.out.println("Image not loaded");
        }
		
	}
}
